import React, { useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
import { EditTable, Input, Button } from '@block/plug';
import { getUUid } from '@src/utils';
import { CompleteTimePicker, EmpSelect } from '@src/aud-sys-component';
import { BusinessFeedbackRow } from '../../types';
import { BUSINESS_TABLE_MAX, RECTIFY_MAX_LENGTH } from '../../constant';
import './BusinessFeedbackTable.scss';

const {
  Column,
  Column: { Content, Console },
} = EditTable;

/**
 * 业务方反馈 可编辑表格
 */

interface Props extends DefaultToEditItem {
  onChange?: (val: BusinessFeedbackRow[]) => void;
  mode?: Mode;
  value?: BusinessFeedbackRow[];
}

interface Handle {
  /** 表单校验 */
  onValidate?: () => boolean;
}

const BusinessFeedbackTable = forwardRef<Handle, Props>((props, ref) => {
  const { onChange, value, mode } = props;

  const tableRef = useRef<EditTable>();

  /** 更新表格父级组件数据 */
  const handleUpdate = () => {
    const data = tableRef.current?.getData();
    onChange?.(data);
  };

  /** 添加行 */
  const handleAddRow = () => {
    if (tableRef.current) {
      const data = tableRef.current?.getData();
      data?.push({ businessFeedbackId: getUUid('string') });
      tableRef.current?.setData(data);
      handleUpdate();
    } else {
      onChange?.([{ businessFeedbackId: getUUid('string') as string }]);
    }
  };

  /**
   * 表单change事件
   */
  const handleTableChange = (column: string, val, index: number) => {
    switch (column) {
      case 'planCompleteTime': {
        tableRef.current?.setRowData(index, { planCompleteTime: val });
        tableRef.current?.validateRow(index, ['planCompleteTime']);
        break;
      }
      case 'rectifyCompletion': {
        tableRef.current?.setRowData(index, { rectifyCompletion: val, planCompleteTime: null });
        tableRef.current?.validateRow(index, ['planCompleteTime']);
        break;
      }
      default:
        break;
    }
    handleUpdate();
  };

  useEffect(() => {
    tableRef.current?.setEditable(mode === 'edit');
  }, [mode, value]);

  useImperativeHandle(ref, () => ({ onValidate: tableRef.current?.validate }));

  return (
    <div className="business-feedback-table">
      {value?.length > 0 && (
        <EditTable
          ref={tableRef}
          className="edit-table"
          defaultData={value}
          scroll={{ x: true }}
          validateTableOnSave={false}
          onCellValueChange={(dataKey, val, { index }) => handleTableChange(dataKey, val, index)}
        >
          <Column dataKey="number" editable={false} width="55px" render={(values, row, obj, { index: i }) => i + 1}>
            编号
          </Column>
          <Column
            dataKey="rectifyContent"
            width="300px"
            rules={[{ required: true, whitespace: true, message: '请输入改进工作具体内容' }]}
            render={(rectifyContentValue) => rectifyContentValue || '-'}
            renderEditor={() => {
              return (
                <Content>
                  <Input.TextArea
                    toContent
                    maxLength={RECTIFY_MAX_LENGTH}
                    showCount
                    placeholder={`请输入改进工作具体内容，输入不超过${RECTIFY_MAX_LENGTH}字符`}
                    autosize={{ minRows: 3 }}
                  />
                </Content>
              );
            }}
          >
            改进工作具体内容
          </Column>
          <Column
            dataKey="personInChargeOfTheRectify"
            width="200px"
            render={(empList: EmpOption[]) => <EmpSelect value={empList} lineBreak mode={mode} />}
            rules={[
              { required: true, message: '请选择改进负责人', type: 'array' },
              {
                validator: (config, values: EmpOption[], callback: (str?: string) => void) => {
                  if (values?.length > 5) callback('最多可选5人');
                  else callback();
                },
              },
            ]}
            renderEditor={() => (
              <Content>
                <EmpSelect
                  toContent
                  mode={mode}
                  placeholder="请选择改进负责人"
                  popLayer={{
                    width: 300,
                    getContainer: () => document.querySelector('.project-detail-content') || document.body,
                  }}
                />
              </Content>
            )}
          >
            改进负责人
          </Column>
          <Column
            dataKey="planCompleteTime"
            width="160px"
            render={(val: number, row: BusinessFeedbackRow) => {
              const { planCompleteTime, rectifyCompletion } = row ?? {};
              return (
                <CompleteTimePicker
                  planCompleteTime={planCompleteTime}
                  rectifyCompletion={rectifyCompletion}
                  mode={mode}
                />
              );
            }}
            rules={[
              {
                validator: (config, val, callback: (str?: string) => void, row: BusinessFeedbackRow) => {
                  const { planCompleteTime, rectifyCompletion } = row ?? {};
                  if (Number.isInteger(planCompleteTime) || rectifyCompletion) callback();
                  else callback('请选择预计完成时间');
                },
              },
            ]}
            renderEditor={(val: number, row: BusinessFeedbackRow, column, { index }) => {
              const { planCompleteTime, rectifyCompletion } = row ?? {};
              return (
                <Content>
                  <CompleteTimePicker
                    planCompleteTime={planCompleteTime}
                    rectifyCompletion={rectifyCompletion}
                    // @ts-expect-error
                    onChange={(key, time) => handleTableChange(key, time, index)}
                    mode={mode}
                  />
                </Content>
              );
            }}
          >
            预计完成时间
          </Column>
          {mode === 'edit' && (
            <Column
              width="55px"
              dataKey="operate"
              renderEditor={(val: unknown, row: BusinessFeedbackRow, column: unknown, { index }) => {
                return (
                  <Console
                    operate={[
                      {
                        label: '删除',
                        disabled: value.length <= 1,
                        onClick: () => {
                          // @ts-expect-error
                          tableRef.current?.removeRow(index);
                          handleUpdate();
                        },
                      },
                    ]}
                  />
                );
              }}
            >
              操作
            </Column>
          )}
        </EditTable>
      )}
      {mode === 'edit' && (
        <Button
          type="primary"
          shape="text"
          disabled={value?.length >= BUSINESS_TABLE_MAX}
          icon="file-add-o"
          onClick={handleAddRow}
        >
          添加
        </Button>
      )}
    </div>
  );
});
export default BusinessFeedbackTable;
